package seismosurfer.util;

import java.util.Properties;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import com.bbn.openmap.util.PropUtils;

/**
 * This class is used to encapsulate all
 * email related operations.
 *
 */
public class EmailService {
    private static final String MESSAGE = "Thank you for using Seismo-Surfer!";

    private static final String SUBJECT = "Seismo-Surfer password request";

    public EmailService() {
    }
    
    /**
     * Send an email to a user to remind
     * them their password.
     * 
     * @param to the email address of the user
     * @param password the user password
     */
    public static void send(String to, String password) {
        Assert.notNull(to, "Recipient`s address cannot be null.");
        Assert.notNull(password, "We cannot send a null password.");

        String message = MESSAGE + "\n\n" + "Your password is: " + password;

        Properties p = Registry.getEmailProperties();

        String hostName = p.getProperty("mail.smtp.host").trim();
        Assert.notNull(hostName, "Mail server host should not be null.");

        int smtpPort = PropUtils.intFromProperties(p, "mail.smtp.port", 25);

        String authUserName = p.getProperty("mail.authentication.username")
                .trim();
        Assert.notNull(hostName, "Authentication username should not be null.");

        String authPassword = p.getProperty("mail.authentication.password")
                .trim();
        Assert.notNull(hostName, "Authentication password should not be null.");

        String fromEmail = p.getProperty("mail.from.email").trim();
        Assert.notNull(hostName, "From email should not be null.");

        String fromName = p.getProperty("mail.from.name").trim();
        Assert.notNull(hostName, "From name should not be null.");

        try {
            SimpleEmail email = new SimpleEmail();
            email.setHostName(hostName);
            email.setSmtpPort(smtpPort);
            email.setAuthentication(authUserName, authPassword);
            email.addTo(to);
            email.setFrom(fromEmail, fromName);
            email.setSubject(SUBJECT);
            email.setMsg(message);
            email.send();
        } catch (EmailException ex) {
            throw new SeismoException("There was a problem sending email.", ex);
        }

    }

}